package com.estronger.shopmanage.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.hardware.input.InputManager;
import android.os.Looper;
import android.provider.MediaStore;
import android.widget.ImageView;
import com.estronger.shopmanage.base.MyApplication;
import com.luck.picture.lib.PictureSelector;
import com.soonfor.evaluate.http.httptools.AsyncUtils;
import com.soonfor.evaluate.tools.ImageUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VideoUtils {

    interface VideoUtilsListener{
        void onCompleted(VideoItem item);
    }

    Map<String,VideoItem> itemMap = new HashMap<>();

    Context mContext;
    public VideoUtils(Context c){
        this.mContext = c;
    }

    public void showVideo(String url, final ImageView imageView){
        String key = stringToMd5(url);
        if (key == null){
            return;
        }
        VideoItem videoItem = null;
        if (!itemMap.containsKey(key)){
            videoItem = new VideoItem();
            itemMap.put(key,videoItem);
        }else {
            videoItem = itemMap.get(key);
        }
        if (videoItem.inDown){
            Toast.show(mContext,"视频加载中，请稍后再试",Toast.LENGTH_LONG);
            return;
        }
        if (videoItem.dowloaded){
            imageView.setImageBitmap(videoItem.thuImgBitmap);
            PictureSelector.create((Activity) mContext).externalPictureVideo(videoItem.videoPath);
        }else {
            startDownLoad(key,url, videoItem, new VideoUtilsListener() {
                @Override
                public void onCompleted(VideoItem item) {
                    PictureSelector.create((Activity) mContext).externalPictureVideo(item.videoPath);
                    imageView.setImageBitmap(item.thuImgBitmap);
                }
            });
        }
    }

    public void showVideoThumbImgeToImgeView(String url,final ImageView imageView){
        String key = stringToMd5(url);
        if (key == null){
            Toast.show(mContext,"播放出错，请重试",Toast.LENGTH_LONG);
            return;
        }
        VideoItem videoItem = null;
        if (!itemMap.containsKey(key)){
            videoItem = new VideoItem();
            itemMap.put(key,videoItem);
        }else {
            videoItem = itemMap.get(key);
        }
        if (videoItem.inDown){
            Toast.show(mContext,"视频加载中，请稍后再试",Toast.LENGTH_LONG);
            return;
        }
        if (videoItem.dowloaded){
            imageView.setImageBitmap(videoItem.thuImgBitmap);
        }else {

            startDownLoad(key,url, videoItem, new VideoUtilsListener() {
                @Override
                public void onCompleted(VideoItem item) {
                    imageView.setImageBitmap(item.thuImgBitmap);
                }
            });
        }
    }

    void startDownLoad(final String key, final String url, final VideoItem videoItem, final VideoUtilsListener listener){

        String local = getAllDataFileName(key);
        if (local != null){
            String path = local;
            videoItem.inDown = false;
            videoItem.dowloaded = true;
            videoItem.videoPath = path;
            videoItem.thuImgBitmap = ImageUtils.getVideoThumbnail(path,
                    500,500,
                    MediaStore.Images.Thumbnails.FULL_SCREEN_KIND);
            listener.onCompleted(videoItem);
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                downLoadVideo(key,url, videoItem, new VideoUtilsListener() {
                    @Override
                    public void onCompleted(final VideoItem item) {
                        ((Activity)mContext).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                listener.onCompleted(item);
                            }
                        });
                    }
                });
            }
        }).start();
    }

    void downLoadVideo(String key,String url, final VideoItem videoItem, final VideoUtilsListener listener) {
        videoItem.inDown = true;
        String name = key + ".mp4";
        String dir = mContext.getCacheDir().getAbsolutePath();
        AsyncUtils.download(url, name, dir, new AsyncUtils.NetWorkListenner() {
            @Override
            public void onSuccess(Object object) {
                if (object instanceof Map){
                    String path = (String) ((Map) object).get("path");
                    videoItem.inDown = false;
                    videoItem.dowloaded = true;
                    videoItem.videoPath = path;
                    videoItem.thuImgBitmap = ImageUtils.getVideoThumbnail(path,
                            500,500,
                            MediaStore.Images.Thumbnails.FULL_SCREEN_KIND);
                    if (listener != null){
                        listener.onCompleted(videoItem);
                    }
                }
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }

    /**
     * 获取dataFile文件夹下的所有文件
     * */
    public String getAllDataFileName(String key){
        // 文件夹路径
        String dir = mContext.getCacheDir().getAbsolutePath();
        ArrayList<String> fileList = new ArrayList<>();

        File file = new File(dir);
        File[] tempList = file.listFiles();
        String path = null;
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                String name = tempList[i].getName();
                name = name.replace(".mp4","");
                if (name.equals(key)){
                    path = tempList[i].getAbsolutePath();
                    break;
                }
            }
        }
        return path;
    }

    class VideoItem{
        String url;
        String videoPath;
        Bitmap thuImgBitmap;
        boolean inDown;
        boolean dowloaded;
    }

    public String stringToMd5(String psw) {
        {
            try {
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                md5.update(psw.getBytes("UTF-8"));
                byte[] encryption = md5.digest();

                StringBuffer strBuf = new StringBuffer();
                for (int i = 0; i < encryption.length; i++) {
                    if (Integer.toHexString(0xff & encryption[i]).length() == 1) {
                        strBuf.append("0").append(Integer.toHexString(0xff & encryption[i]));
                    } else {
                        strBuf.append(Integer.toHexString(0xff & encryption[i]));
                    }
                }

                return strBuf.toString();
            } catch (NoSuchAlgorithmException e) {
                return "";
            } catch (UnsupportedEncodingException e) {
                return "";
            }
        }
    }
}
